<template>
  <a-spin :spinning="confirmLoading">
    <a-form ref="formRef" class="antd-modal-form" :labelCol="labelCol" :wrapperCol="wrapperCol">
      <a-row>
        <a-col :span="8">
          <a-form-item label="送检日期" v-bind="validateInfos.checkDate">
            <a-date-picker v-model:value="formData.checkDate" value-format="YYYY-MM-DD" style="width: 100%"
              :disabled="disabled" />
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="送检人" v-bind="validateInfos.checkPer">
            <a-input v-model:value="formData.checkPer" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="8">
          <a-form-item label="备注" v-bind="validateInfos.remark">
            <a-input style="width:800px;" v-model:value="formData.remark" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
      </a-row>
      
    </a-form>
  </a-spin>
  <BasicTable @register="registerTable" :columns="checkColumns" :dataSource="dataValue" :disabled="disabled">
    <template #action="{ record }">
      <TableAction :actions="getTableAction(record)" />
    </template>
  </BasicTable>
</template>

<script lang="ts" setup>
import { ref, reactive, defineExpose, nextTick, defineProps, computed } from 'vue';
import { useMessage } from '/@/hooks/web/useMessage';
import { getValueType } from '/@/utils';
import { saveOrUpdate, queryAll, checkId } from '../LabUtensilCheck.api';
import { Form } from 'ant-design-vue';
import { checkColumns } from '../../utensil_checkList/LabUtensilChecklist.data';
import { useListPage } from '/@/hooks/system/useListPage';
import { BasicTable, TableAction } from '/@/components/Table';

const props = defineProps({
  formDisabled: { type: Boolean, default: false },
  formData: { type: Object, default: () => { } },
  formBpm: { type: Boolean, default: true }
});
const formRef = ref();
const useForm = Form.useForm;
const emit = defineEmits(['register', 'ok']);
const formData = reactive<Record<string, any>>({
  id: '',
  checkRef: '',
  checkDate: '',
  checkPer: '',
  department: '',
  annex: '',
  checkState: '',
  remark: '',
});
const { createMessage } = useMessage();
const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 5 } });
const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 16 } });
const confirmLoading = ref<boolean>(false);
//表单验证
const validatorRules = {
};
const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: true });

// 表单禁用
const disabled = computed(() => {
  if (props.formBpm === true) {
    if (props.formData.disabled === false) {
      return false;
    } else {
      return true;
    }
  }
  return props.formDisabled;
});

//注册table数据
const { tableContext } = useListPage({
  tableProps: {
    title: '校验器具',
    canResize: true,
    useSearchForm: false,
    actionColumn: {
      width: 80,
      fixed: 'right',
    },
    showIndexColumn: true,
    showTableSetting: false,
  },

});
const [registerTable] = tableContext;



const dataValue = ref();
/**
 * 新增
 */
async function add() {
  formData.value = [];
  const res = await queryAll();

  dataValue.value = res;
  nextTick(() => {
    resetFields();
    //赋值
    Object.assign(formData);
  });
  // edit({});
}

/**
 * 编辑
 */
async function edit(record) {
  dataValue.value = [];
  dataValue.value = await checkId(record.id);
  nextTick(() => {
    resetFields();
    //赋值
    Object.assign(formData, record);
  });
}

/**
 * 操作栏
 */
function getTableAction(record) {
  return [
    {
      label: '删除',
      color: 'error',
      popConfirm: {
        title: '是否确认删除',
        width: 155,
        confirm: handleDelete.bind(null, record),
      },
      disabled: disabled
    }
  ];
}
function handleDelete(record) {

  dataValue.value = dataValue.value.filter((hon) => hon.uteRef !== record.uteRef)
}


/**
 * 提交数据
 */
async function submitForm() {
  // 触发表单验证
  await validate();
  confirmLoading.value = true;
  const isUpdate = ref<boolean>(false);
  //时间格式化
  let model = formData;
  if (model.id) {
    isUpdate.value = true;
  }
  //循环数据
  for (let data in model) {
    //如果该数据是数组并且是字符串类型
    if (model[data] instanceof Array) {
      let valueType = getValueType(formRef.value.getProps, data);
      //如果是字符串类型的需要变成以逗号分割的字符串
      if (valueType === 'string') {
        model[data] = model[data].join(',');
      }
    }
  }
  model.checkList = JSON.parse(JSON.stringify(dataValue.value));

  await saveOrUpdate(model, isUpdate.value)
    .then((res) => {
      if (res.success) {
        createMessage.success(res.message);
        emit('ok');
      } else {
        createMessage.warning(res.message);
      }
    })
    .finally(() => {
      confirmLoading.value = false;
    });
}


defineExpose({
  add,
  edit,
  submitForm,
});
</script>

<style lang="less" scoped>
.antd-modal-form {
  min-height: auto !important;
  overflow-y: auto;
  padding: 24px 24px 24px 24px;
}
</style>
